import React, { useState, useEffect } from "react"; // 导入 useEffect
import { useRouter } from 'next/navigation'; // 导入 useRouter
// 假设 getProjectList 在 api.ts 中定义
import { updatePlanLevel, getProjectList } from '../services/api'; // 导入 API 函数

import { Project } from '../services/api'; // 导入 Project 接口

interface Plan {
  plans: string[];
  intro: string[];
}

interface MainInterfaceProps {
  plan: Plan | null;
  userLevel: number;
  selectedPlanIndex: number | null;
  language: string;
  direction: string;
  userId: string;
  isLoading: boolean;
  onGoBack: () => void;
  onCreateNewTask: () => void;
  onPlanSelect: (index: number) => void; // 父组件更新选中项的回调
  onLevelUpdate: (newLevel: number) => Promise<void>; // 新增：处理等级更新的回调
}

const MainInterface: React.FC<MainInterfaceProps> = ({
  plan,
  userLevel,
  selectedPlanIndex,
  language,
  direction,
  userId,
  isLoading,
  onGoBack,
  onCreateNewTask,
  onPlanSelect,
  onLevelUpdate, // 新增：解构 props
}) => {
  const router = useRouter(); // 获取 router 实例
  const [projects, setProjects] = useState<Project[]>([]); // 项目列表状态
  const [loadingProjects, setLoadingProjects] = useState<boolean>(true); // 项目加载状态
  const [projectError, setProjectError] = useState<string | null>(null); // 项目加载错误状态
  const [showCompletionMessage, setShowCompletionMessage] = useState(false); // 新增：控制完成提示的显示
  const [completionMessageTimeoutId, setCompletionMessageTimeoutId] = useState<NodeJS.Timeout | null>(null); // 新增: 保存 timeout ID

 const currentIntro = (plan && selectedPlanIndex !== null && selectedPlanIndex >= 0 && selectedPlanIndex < plan.intro.length)
    ? plan.intro[selectedPlanIndex]
    : plan ? "请在左侧选择一个计划点查看介绍。" : "没有可用的计划数据。";

 // 新的处理函数，用于处理计划项点击
 const handlePlanItemClick = (index: number) => {
   // 仅更新选中的计划项（调用父组件传入的回调以更新UI）
   // 不再在此处更新后端的 userLevel
   onPlanSelect(index);
 };

 // useEffect hook to fetch projects...
 useEffect(() => {
   const fetchProjects = async () => {
     // 确保 userId, language, direction 和 selectedPlanIndex 都有效
     if (!userId || !language || !direction || selectedPlanIndex === null) {
       // 如果缺少必要信息或未选择计划步骤，则不加载项目或清空现有项目
       setProjects([]); // 清空项目列表
       setLoadingProjects(false);
       // 可以选择性地设置错误或提示信息
       // setProjectError("请先选择一个计划步骤。");
       return;
     }

     try {
       setLoadingProjects(true);
       setProjectError(null); // 清除之前的错误
       // 调用 getProjectList 并传入所有必需的参数
       const projectList = await getProjectList(userId, language, direction, selectedPlanIndex);
       setProjects(projectList);
     } catch (error: any) {
       console.error("加载项目列表失败:", error);
       setProjectError(error.message || "加载项目时发生未知错误。");
     } finally {
       setLoadingProjects(false);
     }
   };

   fetchProjects();
   // eslint-disable-next-line react-hooks/exhaustive-deps
 }, [userId, language, direction, selectedPlanIndex]); // 当这些依赖项变化时重新获取

 // 新增：处理创建新项目按钮点击事件
 const handleCreateNewProjectClick = () => {
   // 确保已选择计划步骤
   if (plan && selectedPlanIndex !== null && selectedPlanIndex >= 0) {
     const selectedPlanText = plan.plans[selectedPlanIndex];
     const selectedIntroText = plan.intro[selectedPlanIndex];
     const step = selectedPlanIndex;

     // 使用 URLSearchParams 来构建和编码查询字符串
     const queryParams = new URLSearchParams({
       userId: userId,
       plan: selectedPlanText,
       intro: selectedIntroText,
       lang: language,
       direction: direction,
       step: step.toString(),
        // 将步骤索引转换为字符串
     });

     // 跳转到新项目页面，并附带查询参数
     router.push(`/new_proj?${queryParams.toString()}`);
   } else {
     // 如果没有选择计划步骤，可以选择提示用户或禁用按钮
     // 这里暂时只在控制台输出警告
     console.warn("在创建新项目之前，请先选择一个计划步骤。");
     // 考虑添加一个用户提示，例如使用 alert() 或更友好的UI通知
     // alert("请先选择一个计划步骤。");
   }
 };

 // 修改：处理“标记为已完成”按钮点击
 const handleMarkAsComplete = async () => {
   // 清除可能存在的旧计时器
   if (completionMessageTimeoutId) {
     clearTimeout(completionMessageTimeoutId);
     setCompletionMessageTimeoutId(null); // 清除旧 ID
   }

   if (selectedPlanIndex !== null && selectedPlanIndex === userLevel) {
     const nextLevel = userLevel + 1;
     try {
       // 1. 调用父组件的更新函数，它会处理后端和父组件状态更新（可能触发刷新）
       await onLevelUpdate(nextLevel);

       // 2. 更新成功后，显示提示信息
       setShowCompletionMessage(true);

       // 3. 设置 3 秒后自动隐藏提示
       const timeoutId = setTimeout(() => {
         setShowCompletionMessage(false);
         setCompletionMessageTimeoutId(null); // 清除 timeout ID
       }, 3000);
       setCompletionMessageTimeoutId(timeoutId); // 保存新的 timeout ID

       // 移除这里的 onPlanSelect 调用，父 hook 会处理
       // if (plan && nextLevel < plan.plans.length) {
       //    onPlanSelect(nextLevel); // <--- REMOVE THIS
       // }

     } catch (error) {
       console.error("标记完成失败:", error);
       // 可以在这里添加错误提示
       // 确保即使出错也隐藏可能残留的消息
       setShowCompletionMessage(false);
       if (completionMessageTimeoutId) clearTimeout(completionMessageTimeoutId);
       setCompletionMessageTimeoutId(null);
     }
   }
 };

 // 新增：处理关闭提示按钮
 const handleCloseCompletionMessage = () => {
   if (completionMessageTimeoutId) {
     clearTimeout(completionMessageTimeoutId); // 清除计时器
     setCompletionMessageTimeoutId(null);
   }
   setShowCompletionMessage(false); // 隐藏提示
 };

 // 清理副作用：组件卸载时清除计时器
 useEffect(() => {
   return () => {
     if (completionMessageTimeoutId) {
       clearTimeout(completionMessageTimeoutId);
     }
   };
 }, [completionMessageTimeoutId]);


 return (
   // 添加 relative 定位以便绝对定位子元素
   <div className="relative flex flex-col md:flex-row w-screen h-screen bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100">
      {/* 左侧边栏 */}
      <div className="w-full md:w-72 bg-white dark:bg-gray-800 p-4 flex flex-col justify-between border-r border-gray-200 dark:border-gray-700 flex-shrink-0 overflow-y-auto">
        <div>
          {/* 返回按钮 */}
          <button
            onClick={onGoBack}
            className="mb-4 text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-200 flex items-center"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
            </svg>
            返回选择
          </button>

          <h2 className="text-lg font-semibold mb-4">
              计划: {language || 'N/A'} - {direction || 'N/A'}
          </h2>
          {plan && plan.plans.length > 0 ? (
            <div>
              {plan.plans.map((planItem, index) => {
                const isCompleted = index < userLevel; // 基于传入的 userLevel 判断
                const isLocked = index > userLevel;    // 基于传入的 userLevel 判断
                return (
                  <div
                    key={index}
                    // 修改 onClick 调用新的处理函数
                    onClick={!isLocked ? () => handlePlanItemClick(index) : undefined}
                    className={`pl-2 py-1.5 my-1 flex items-center justify-between ${isLocked ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'} rounded transition-colors duration-150 ${
                      index === selectedPlanIndex
                        ? 'text-blue-600 font-bold bg-blue-100 dark:bg-blue-900 dark:text-blue-300 border-l-4 border-blue-500'
                        : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
                    } ${isCompleted ? 'line-through text-gray-400 dark:text-gray-500' : ''}`} // 调整已完成样式
                  >
                    <span>{planItem}</span>
                    {isLocked && <span className="text-xs text-gray-400 dark:text-gray-500 ml-2">🔒</span>}
                  </div>
                );
              })}
           </div>
         ) : (
           <p className="text-gray-500 dark:text-gray-400">
              {isLoading ? '正在加载...' : '无计划步骤。'}
            </p>
          )}
        </div>
        <div className="mt-auto pt-4 border-t border-gray-200 dark:border-gray-700">
          <p className="text-sm text-gray-500 dark:text-gray-400">用户 ID: {userId}</p>
          <button
            onClick={onCreateNewTask}
            className="w-full mt-4 bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded transition-colors duration-150"
          >
            创建新任务
          </button>
        </div>
      </div>

      {/* 主内容区 */}
      <div className="flex-1 flex flex-col p-6 overflow-y-auto">
        <div className="mb-6 bg-white dark:bg-gray-800 p-4 rounded shadow">
          <h3 className="text-md font-semibold mb-2 text-gray-800 dark:text-gray-200">计划介绍</h3>
          <p className="text-sm text-gray-600 dark:text-gray-400 whitespace-pre-wrap">
            {isLoading ? '加载中...' : currentIntro}
          </p>
        </div>
        {/* 项目管理器容器 */}
        <div className="flex-1 bg-white dark:bg-gray-800 p-6 rounded shadow mt-6 md:mt-0"> {/* 添加 mt-6 或 md:mt-0 */}
          <h1 className="text-2xl font-bold mb-4 text-gray-900 dark:text-gray-100">项目管理器</h1>
          {/* 加载状态 */}
          {loadingProjects && (
            <p className="text-gray-500 dark:text-gray-400">正在加载项目...</p>
          )}
          {/* 错误状态 */}
          {projectError && (
            <p className="text-red-500 dark:text-red-400">错误: {projectError}</p>
          )}
          {/* 项目网格 */}
          {!loadingProjects && !projectError && (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
              {/* 渲染现有项目 */}
              {projects.slice(0, 8).map((project, project_index) => ( // 获取项目索引
                <div
                  key={project.id}
                  className="bg-gray-100 dark:bg-gray-700 p-4 rounded-lg shadow cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors duration-150 flex items-center justify-center h-32" // 添加固定高度 h-32
                  onClick={() => { // 更新 onClick 逻辑
                    if (selectedPlanIndex !== null) { // 确保已选择计划步骤
                      const queryParams = new URLSearchParams({
                        user_id: userId,
                        lang: language,
                        direction: direction,
                        step: selectedPlanIndex.toString(),
                        project_index: project_index.toString(), // 传递项目索引
                      });
                      router.push(`/project_page?${queryParams.toString()}`); // 跳转到 /project_page
                    } else {
                      console.warn("请先选择一个计划步骤，然后再打开项目。");
                      // 可以考虑添加用户提示
                    }
                  }}
                >
                  <span className="text-center text-sm font-medium text-gray-800 dark:text-gray-200">{project.name}</span>
                </div>
              ))}
              {/* 创建新项目按钮 (如果项目少于9个) */}
              {projects.length < 9 && (
                <div
                  className="bg-blue-100 dark:bg-blue-900 p-4 rounded-lg shadow cursor-pointer hover:bg-blue-200 dark:hover:bg-blue-800 transition-colors duration-150 flex items-center justify-center h-32" // 添加固定高度 h-32
                  // 修改 onClick 调用新的处理函数
                  onClick={handleCreateNewProjectClick}
                >
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-10 w-10 text-blue-600 dark:text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
                  </svg>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

       {/* 新增：标记为已完成按钮 (绝对定位在右下角) */}
       {plan && selectedPlanIndex !== null && selectedPlanIndex === userLevel && selectedPlanIndex < plan.plans.length && (
        <button
          onClick={handleMarkAsComplete}
          className="absolute bottom-6 right-6 bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2 px-4 rounded-lg shadow-md transition-colors duration-150 flex items-center z-10" // 添加 z-10 确保按钮在最上层
        >
          <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
            <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
          </svg>
          标记为已完成
        </button>
      )}

       {/* 新增：完成提示信息 (绝对定位在右下角，按钮上方) */}
       {showCompletionMessage && (
         <div className="absolute bottom-20 right-6 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg shadow-lg flex items-center justify-between z-20 animate-fade-in-up" role="alert"> {/* 添加 z-20 和动画 */}
           <div>
             <strong className="font-bold">恭喜! 🎉</strong>
             <span className="block sm:inline ml-2">当前任务阶段已完成，下一阶段已解锁！</span>
           </div>
           <button
             onClick={handleCloseCompletionMessage}
             className="ml-4 text-green-500 hover:text-green-700 font-bold"
           >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
               <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
             </svg>
           </button>
         </div>
       )}

       {/* 简单的 CSS 动画 (可以添加到 globals.css 或使用 Tailwind 配置) */}
       {/*
       @keyframes fade-in-up {
         from { opacity: 0; transform: translateY(10px); }
         to { opacity: 1; transform: translateY(0); }
       }
       .animate-fade-in-up {
         animation: fade-in-up 0.3s ease-out forwards;
       }
       */}
    </div>
  );
};

export default MainInterface;